# -*- coding: utf-8 -*-
import traceback
from functools import wraps
from webhelpers import paginate
from flask import request, redirect, url_for, render_template, session, flash
from sys2do.constant import TAB_FLAG, MESSAGE_ERROR, MSG_NO_PERMISSION
from sys2do.util.common import _g
from sys2do.setting import PAGINATE_PER_PAGE
from sys2do.util.logic_helper import getAllPermission, getAnyPermission, \
    inAllGroup, inAnyGroup
import functools
from flask.helpers import jsonify

__all__ = ['templated', 'trycatch', 'loginRequired',
           'allPermission', 'anyPermission', 'allGoup', 'anyGroup',
           'atvtab', 'mypaginate', 'myjson']

def templated( template = None ):
    def decorator( f ):
        @wraps( f )
        def decorated_function( *args, **kwargs ):
            template_name = template
            if template_name is None:
                # template_name = request.endpoint.replace('.', '/') + '.html'
                template_name = "%s.html" % f.__name__

            if args:
                s = args[0]
                if s.template_folder != None:
                    template_name = "%s/%s" % ( s.template_folder.replace( '.', '/' ), template_name )

            ctx = f( *args, **kwargs )
            if ctx is None:
                ctx = {}
            elif not isinstance( ctx, dict ):
                return ctx
            return render_template( template_name, **ctx )
        return decorated_function
    return decorator



def trycatch( default = None ):
    def decorator( f ):
        @wraps( f )
        def _f( *args, **kw ):
            try:
                return f( *args, **kw )
            except:
#                traceback.print_exc()
                return default
        return _f
    return decorator



def loginRequired( f ):
    @wraps( f )
    def decorated_function( *args, **kwargs ):
        if not session.get( 'login', None ):
            return redirect( url_for( 'bpAuth.login', next = request.url ) )
        return f( *args, **kwargs )
    return decorated_function


def _checkPermission( func, *params ):
    def decorator( f ):
        @wraps( f )
        def decorated_function( *args, **kwargs ):
            if not func( *params ):
                flash( MSG_NO_PERMISSION, MESSAGE_ERROR )
                return redirect( url_for( 'bpRoot.view', action = 'goto' ) )
            return f( *args, **kwargs )
        return decorated_function
    return decorator



allPermission = functools.partial( _checkPermission, getAllPermission )
anyPermission = functools.partial( _checkPermission, getAnyPermission )
allGroup = functools.partial( _checkPermission, inAllGroup )
anyGroup = functools.partial( _checkPermission, inAnyGroup )


def activetab( tab ):
    def decorator( f ):
        @wraps( f )
        def decorated_function( *args, **kwargs ):
            session[TAB_FLAG] = tab
            return f( *args, **kwargs )
        return decorated_function
    return decorator


def mypaginate( flag ):
    def decorator( f ):
        @wraps( f )
        def decorated_function( *args, **kwargs ):
            result = f( *args, **kwargs )
            if type( result ) == dict and flag in result:
                page = _g( 'page', 1 ) or 1
                def url_for_page( **params ): return url_for( '.view', action = f.__name__, page = params['page'] )
                w = paginate.Page( result[flag], page, show_if_single_page = True,
                                  items_per_page = PAGINATE_PER_PAGE, url = url_for_page )
                result[flag] = w
            return result
        return decorated_function
    return decorator


def myjson():
    def decorator( f ):
        @wraps( f )
        def decorated_function( *args, **kwargs ):
            ctx = f( *args, **kwargs )
            return jsonify( ctx )
        return decorated_function
    return decorator
